import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/face_model/face_result_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_info.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:lottie/lottie.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';

class FaceRecognitionWebviewPage extends StatefulWidget {
  static const String path = '/faceRecognitionWebviewPage';
  
  const FaceRecognitionWebviewPage({super.key});

  @override
  State<FaceRecognitionWebviewPage> createState() => _FaceRecognitionWebviewPageState();
}

class _FaceRecognitionWebviewPageState extends State<FaceRecognitionWebviewPage> {
  late String _url;
  late InAppWebViewController _webViewController;
  bool _permissionsGranted = false;

  final GlobalKey _webViewKey = GlobalKey();
  final RxDouble _progress = 0.0.obs;
  final RxString _currentUrl = ''.obs;
  final GlobalController globalController = Get.find();

  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _initializeData();

  }

  void _initializeData() {
    try {
      final params = Get.parameters ?? {};
      final args = Get.arguments ?? {};
      final urlParam = params['url'] ?? args['url'];

      _checkPermissions();
      if (urlParam != null && urlParam.isNotEmpty) {
        _url = Uri.decodeComponent(urlParam);
      } else {
        _showErrorAndGoBack('URL 无效');
      }
    } catch (e) {
      debugPrint('解析 URL 失败: $e');
      _showErrorAndGoBack('URL 格式不正确');
    }
  }

  void _showErrorAndGoBack(String message) {
    Get.back();
    Get.snackbar(
      '错误',
      message,
      snackPosition: SnackPosition.TOP,
    );
  }

  @override
  Widget build(BuildContext context) {
    final statusBarHeight = MediaQuery.of(context).padding.top;
    return PopScope(
      canPop: true,
      onPopInvoked: (didPop) {
        if (!didPop) {
          _handleBack();
        }
      },
      child:Obx(() => SafeArea(
        child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CustomAppBar2(title: '人脸识别', context: context),
        body: Column(
            children: [
              SizedBox(height: statusBarHeight),
              _buildProgressBar(),
              Expanded(
                child: _buildWebView(),
              ),
              SizedBox(height: statusBarHeight),
            ],
          ), 
        ))
      ), 
    );
  }

  Widget _buildProgressBar() {
    return LinearProgressIndicator(
      minHeight: 1.px,
      color: const Color(0xFFF3F3F3),
      value: _progress.value,
    );
  }

  Widget _buildWebView() {
    return InAppWebView(
      key: _webViewKey,
      initialUrlRequest: URLRequest(
        url: WebUri(_url),
      ),
      initialOptions: InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          useShouldOverrideUrlLoading: true,
          javaScriptEnabled: true,
          javaScriptCanOpenWindowsAutomatically: true,
        ),
        android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
          allowFileAccess: true,
        ),
        ios: IOSInAppWebViewOptions(
          allowsInlineMediaPlayback: true,
          isFraudulentWebsiteWarningEnabled: false
        ),
      ),
      onWebViewCreated: (controller) {
        _webViewController = controller;
      },
      onLoadStart: (controller, url) {
        _currentUrl.value = url?.toString() ?? '';
            debugPrint('加载: ${_currentUrl.value}');

      },
      onProgressChanged: (controller, progress) {
        _progress.value = progress / 100;
      },
      shouldOverrideUrlLoading: (controllers, navigationAction) async {
        return _handleUrlNavigation(navigationAction);
      },
       onPermissionRequest: (controller, request) async {
        // 处理网页内的权限请求
        return PermissionResponse(
          resources: request.resources,
          action: PermissionResponseAction.GRANT
        );
      },
    );
  }

  NavigationActionPolicy _handleUrlNavigation(NavigationAction navigationAction) {
    final uri = navigationAction.request.url;
    debugPrint('拦截检测: ${uri?.toString()}');
    
    // 拦截特定域名
    if (uri?.toString().contains("https://www.baidu.com") == true) {
      // Navigator.of(context).pop();
      startTime();
      return NavigationActionPolicy.CANCEL;
    }
    
    return NavigationActionPolicy.ALLOW;
  }

  Future<bool> _handleBack() async {
    try {
      final canGoBack = await _webViewController.canGoBack();
      if (canGoBack) {
        await _webViewController.goBack();
        return false; // 阻止默认返回
      }
    } catch (e) {
      debugPrint('处理返回操作失败: $e');
    }
    
    return true; // 允许系统返回
  }
  Future<void> _checkPermissions() async {
    // 请求摄像头和麦克风权限
    final status = await [Permission.camera, Permission.microphone].request();
    
    if (status[Permission.camera]!.isGranted && 
        status[Permission.microphone]!.isGranted) {
      setState(() => _permissionsGranted = true);
    } else {
      Get.snackbar('权限被拒绝', '请前往设置开启权限');
    }
  }

  void startTime(){
    EasyLoading.show(
      indicator: Lottie.asset(
        'static/json/kongfu.json',
        width: 40.px,
        height: 40.px,
      ),
      dismissOnTap: false,
    );
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      payResult();
    });
  }

  int count = 0;
  Future<void> payResult()async {
    count += 1;
    if(count<=3){
      await http.netFetch<FaceResultModel>(
        ApiUrl.getFaceGetResult,
        method: Method.post,
        success: (result) {
          if (result.code == 200) {
            if(result.data?.status == false){
              EasyLoading.dismiss();
              _timer?.cancel();
              Get.toNamed(SettingRealNameInfo.path);//认证成功
              globalController.getUserInfo(success: (p0) => {
                debugPrint('更新用户信息成功'),
              });
            } else {
              return;
            }
          }
        },
      );
    }else{
      EasyLoading.dismiss();
      count = 0;
      _timer?.cancel();
      Navigator.of(context).pop();
      showToast('人脸认证失败，请重试');
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}